<template>
    <div class="page-wrap">
        <div class="page-cont">
            <div v-if="treeData">
                <flexbox>
                    <span>产线/产品：</span>
                    <SelectCatalogCode v-model:value="catalogCode" :defaultTreeData="treeData" @change="handleCascaderChange" />
                </flexbox>
                <a-divider style="margin: 12px 0" />
            </div>
            <flexbox align="flex-start">
                <div style="width: 60px; padding-top: 2px">产品线：</div>
                <div style="flex: 1">
                    <flexbox wrap="wrap">
                        <a-checkable-tag
                            :checked="checkedLine === index"
                            v-for="(item, index) of lineOptions"
                            :key="index"
                            @change="handleChangeLine($event, index)"
                            style="margin-bottom: 8px"
                        >
                            {{ item.catalogName }}
                        </a-checkable-tag>
                    </flexbox>
                </div>
            </flexbox>

            <flexbox align="flex-start" class="margin-t-8">
                <div style="width: 60px; padding-top: 2px">产品：</div>
                <div style="flex: 1">
                    <flexbox wrap="wrap">
                        <a-checkable-tag
                            :checked="checkedPro === index"
                            v-for="(item, index) of proOptions"
                            :key="index"
                            @change="handleChangePro($event, index)"
                            style="margin-bottom: 8px"
                        >
                            {{ item.catalogName }}
                        </a-checkable-tag>
                    </flexbox>
                </div>
            </flexbox>
            <a-divider style="margin: 6px 0 12px 0" />
            <FilterForm @change="handleChangeSearchQuery" />
        </div>

        <CardList :list="list" :searchQuery="searchQuery" :queryArr="queryArr" @getItemData="getItemData" v-loading="loading" />
    </div>
</template>

<script lang="ts">
import api from '@/api';
import { treeFilter } from '@/utils/tree';
import { SelectCatalogCode } from '@/components';
import CardList from '@/views/energyManage/beijixing/components/CardList.vue';
import FilterForm from './components/FilterForm.vue';
import { defineComponent, reactive, toRefs } from 'vue';
export default defineComponent({
    components: {
        FilterForm,
        CardList,
        SelectCatalogCode
    },
    setup() {
        const state = reactive<any>({
            checkedLine: 0,
            checkedPro: -1,
            lineOptions: [],
            proOptions: [],
            treeData: null,
            searchQuery: {},
            list: [],
            loading: false,
            queryArr: [],
            catalogCode: ''
        });
        const handleChangeLine = (val, index) => {
            if (val) {
                state.checkedLine = index;
                getProOptions([state.treeData[index]]);
            }
        };
        // 选择产品
        const handleChangePro = (val, index) => {
            if (val) {
                state.checkedPro = index;
                getList();
            }
        };
        // 查询所有数据
        const getList = async () => {
            state.loading = true;
            if (state.checkedPro === 0) {
                state.catalogCode = state.lineOptions[state.checkedLine].catalogCode;
                // 如果是全部，参数有两种情况：1 有子产品的传递子产品code拼接成的字符串 2.没有子产品的传递自身的code
                state.queryArr = state.proOptions.slice(1).map((item) => {
                    if (item.subNodes && item.subNodes.length) {
                        const codeStr = item.subNodes.map((item) => item.node.catalogCode).join(',');
                        return {
                            catalogCode: `${item.catalogCode},${codeStr}`,
                            catalogType: '1'
                        };
                    } else {
                        return {
                            catalogCode: item.catalogCode,
                            catalogType: '1'
                        };
                    }
                });
            }
            // 不是全部，点击某个产品，1.传自身产品code 2.有子产品的，遍历所有子产品的code
            else {
                const item = state.proOptions[state.checkedPro];
                state.catalogCode = item.catalogCode;
                if (item.subNodes && item.subNodes.length) {
                    const codeArr = item.subNodes.map((item) => ({
                        catalogCode: item.node.catalogCode,
                        catalogType: '2'
                    }));
                    const codeStr = item.subNodes.map((item) => item.node.catalogCode).join(',');
                    state.queryArr = [
                        {
                            catalogType: '1',
                            catalogCode: `${item.catalogCode},${codeStr}`
                        },
                        ...codeArr
                    ];
                } else {
                    state.queryArr = [
                        {
                            catalogType: '1',
                            catalogCode: item.catalogCode
                        }
                    ];
                }
            }
            let allRequestAArr = [];
            let allRequestBArr = [];
            if (state.proOptions.length) {
                allRequestAArr = state.queryArr.map(async (item) => {
                    const res = await api.portalControlModel.getPolarisIndexBoard({
                        ...state.searchQuery,
                        catalogCode: item.catalogCode,
                        catalogType: item.catalogType
                    });
                    return res;
                });
                allRequestBArr = state.queryArr.map(async (item) => {
                    const res = await api.portalControlModel.getQualityBoar({
                        ...state.searchQuery,
                        catalogCode: item.catalogCode,
                        catalogType: item.catalogType
                    });
                    return res;
                });
                const list: any = [];
                const resA = await Promise.allSettled(allRequestAArr);
                resA.forEach((item: any) => {
                    const { success, moule } = item.value;
                    if (success) {
                        if (moule.pmpProductDetailDTO.isOutsideSystem === '0') {
                            list.push({
                                isRequireAnalyse: '否',
                                deliveryMode: null,
                                ...moule
                            });
                        } else {
                            list.push(moule);
                        }
                    }
                });
                const resB = await Promise.allSettled(allRequestBArr);
                resB.forEach((item: any, index) => {
                    const { success, moule } = item.value;
                    if (success) {
                        if (moule) {
                            list[index] = {
                                ...list[index],
                                ...moule
                            };
                        }
                    }
                });
                state.list = [...list];
            }
            state.loading = false;
        };
        // 请求某个外采数据
        const getItemData = async ({ index, item }) => {
            const { success, moule } = await api.portalControlModel.getPolarisIndexBoard({
                ...state.searchQuery,
                catalogCode: state.queryArr[index].catalogCode,
                catalogType: state.queryArr[index].catalogType,
                isRequireAnalyse: item.isRequireAnalyse,
                deliveryMode: item.deliveryMode
            });
            if (success) {
                state.list[index] = { ...state.list[index], ...moule, isRequireAnalyse: item.isRequireAnalyse, deliveryMode: item.deliveryMode };
            }
        };
        const getAllProItem = (treeData) => {
            const arr: any = [];
            const getItem = (data) => {
                data.forEach((item) => {
                    if (item.node.catalogType === '0') {
                        if (item.subNodes && item.subNodes.length) {
                            getItem(item.subNodes);
                        }
                    } else {
                        if (item.node.catalogType === '1') {
                            arr.push({
                                id: item.id,
                                ...item.node,
                                node: item.node,
                                subNodes: item.subNodes || []
                            });
                        }
                    }
                });
            };
            getItem(treeData);
            return arr;
        };
        // 过滤出真正要显示的产品
        const filterProOptions = async (options) => {
            const catalogCode = options.map((item) => item.catalogCode).join(',');
            const query = {
                catalogCode
            };
            const { success, moule } = await api.pbiProductCalendarModel.getManageCatalogCode(query);
            if (success) {
                return moule;
            } else {
                return '';
            }
        };
        const getProOptions = async (treeData) => {
            const proOptions = getAllProItem(treeData);
            const proCatalogCodes = await filterProOptions(proOptions);
            if (proCatalogCodes) {
                state.proOptions = proOptions.filter((item) => proCatalogCodes.indexOf(item.catalogCode) >= 0);
                if (state.proOptions.length) {
                    state.proOptions.unshift({
                        catalogName: '全部'
                    });
                    state.checkedPro = 0;
                    getList();
                }
            } else {
                state.proOptions = [];
            }
        };
        const handleChangeSearchQuery = (val) => {
            state.searchQuery = val;
            if (state.checkedPro >= 0) {
                getList();
            }
        };
        const initOptions = async (catalogCode = '', catalogType = '') => {
            // 看是否有默认值，有默认值说明从外部过来新建的
            if (catalogCode && catalogType) {
                const target: any = treeFilter(state.treeData, (node) => node.node.catalogCode === catalogCode);
                if (target && target.length) {
                    const lineIndex = state.treeData.findIndex((item) => item.node.catalogCode === target[0].node.catalogCode);
                    state.checkedLine = lineIndex;
                    const proOptions = getAllProItem([state.treeData[lineIndex]]);
                    const proCatalogCodes = await filterProOptions(proOptions);
                    if (proCatalogCodes) {
                        state.proOptions = proOptions.filter((item) => proCatalogCodes.indexOf(item.catalogCode) >= 0);
                    } else {
                        state.proOptions = [];
                    }
                    if (state.proOptions.length) {
                        state.proOptions.unshift({
                            catalogName: '全部'
                        });
                    }
                    const proIndex = state.proOptions.findIndex((item) => {
                        if (item.node) {
                            return item.node.catalogCode === target[0].subNodes[0].node.catalogCode;
                        }
                        return false;
                    });
                    state.checkedPro = proIndex;
                    getList();
                } else {
                    getProOptions([state.treeData[0]]);
                }
            } else {
                getProOptions([state.treeData[0]]);
                state.checkedLine = 0;
            }
        };
        const init = async () => {
            // const query = {
            //     type: 1
            // };
            const { success, moule } = await api.portalControlModel.getSystemProductCatalogTreeData();
            if (success) {
                state.treeData = JSON.parse(moule);
                console.log('state.treeData', state.treeData);
                state.lineOptions = state.treeData.map((item) => ({
                    id: item.id,
                    ...item.node
                }));
                if (state.lineOptions.length) {
                    initOptions();
                }
            }
        };
        init();
        const handleCascaderChange = (val) => {
            const { nodeInfo } = val;
            console.log(nodeInfo);
            initOptions(nodeInfo.catalogCode, nodeInfo.catalogType);
        };
        return {
            ...toRefs(state),
            handleChangeLine,
            handleChangePro,
            handleChangeSearchQuery,
            getItemData,
            handleCascaderChange
        };
    }
});
</script>

<style scoped lang="less">
::v-deep(.ant-form-item-label) {
    text-align: left;
}
.page-wrap {
    .page-cont {
        padding: 24px;
        background: #fff;
    }
}
</style>
